<template>
  <div class="map-container">
    <h1>地图探索</h1>
    <div class="controls">
      <button @click="loadActivities" class="action-btn">加载活动数据</button>
      <button @click="toggleNearbyDropdown" class="action-btn">显示附近推荐</button>
      <button @click="locateUser" class="action-btn">定位到我的位置</button>
      
      <!-- 分类选择器 -->
      <select v-model="selectedCategory" @change="searchByCategory" class="category-select">
        <option value="">选择分类</option>
        <option value="咖啡厅">咖啡厅</option>
        <option value="餐厅">餐厅</option>
        <option value="公园">公园</option>
        <option value="商场">商场</option>
        <option value="酒店">酒店</option>
        <option value="医院">医院</option>
        <option value="学校">学校</option>
      </select>
      
      <div class="search-container">
        <input 
          v-model="searchKeyword" 
          @keyup.enter="performSearch" 
          placeholder="搜索地点..." 
          class="search-input"
        />
        <button @click="performSearch" class="action-btn search-button">
          搜索
        </button>
      </div>
      <select v-model="searchRadius" class="radius-select">
        <option value="1000">1公里</option>
        <option value="3000">3公里</option>
        <option value="5000">5公里</option>
      </select>
    </div>
    
    <!-- 分类搜索结果列表 -->
    <div v-if="showCategoryResults" class="category-results" @wheel.stop @touchmove.stop>
      <div class="results-header">
        <h3>附近{{ selectedCategory }} ({{ categoryResults.length }}个结果)</h3>
        <button @click="closeCategoryResults" class="close-results-btn">×</button>
      </div>
      <div class="results-list" @wheel.stop @touchmove.stop>
        <div 
          v-for="(item, index) in categoryResults" 
          :key="index" 
          class="result-item"
          @click="selectCategoryItem(item)"
        >
          <div class="item-icon">{{ getItemIcon(item.category) }}</div>
          <div class="item-content">
            <h4>{{ item.title }}</h4>
            <p class="item-address">{{ item.address }}</p>
            <p class="item-distance">{{ item.distance }}米</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 附近推荐下拉框 -->
    <div v-if="showNearbyDropdown" class="nearby-dropdown" @wheel.stop @touchmove.stop>
      <div class="dropdown-content" @wheel.stop @touchmove.stop>
        <div v-if="mockDataLoading" class="loading">
          正在加载数据...
        </div>
        <div v-else class="nearby-list">
          <div 
            v-for="(item, index) in mockNearbyData" 
            :key="index" 
            class="nearby-item"
            @click="selectNearbyItem(item)"
          >
            <div class="item-icon">{{ getItemIcon(item.category) }}</div>
            <div class="item-content">
              <h3>{{ item.title }}</h3>
              <p class="item-address">{{ item.address }}</p>
              <p class="item-distance">{{ item.distance }}米</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="map-wrapper">
      <BaseMap 
        ref="mapRef"
        :center="center"
        :zoom="zoom"
        :apiKey="mapKey"
        @loaded="onMapLoaded"
        @click="onMapClick"
      >
        <MultiMarker 
          v-for="marker in markers" 
          :key="marker.id"
          :position="marker.position || center"
          :options="marker.options || {}"
          @click="() => onMarkerClick(marker)"
          v-if="marker.position"
        />
        <InfoWindow
          v-if="selectedMarker && selectedMarker.position"
          :visible="infoWindowVisible"
          :position="selectedMarker.position"
          :options="infoWindowOptions"
        >
          <div v-if="selectedMarker.type === 'activity'">
            <h3>{{ selectedMarker.data.name }}</h3>
            <p><strong>地址:</strong> {{ selectedMarker.data.address }}</p>
            <p><strong>描述:</strong> {{ selectedMarker.data.description || '暂无描述' }}</p>
            <p><strong>类别:</strong> {{ getCategoryLabel(selectedMarker.data.category) }}</p>
          </div>
          <div v-else-if="selectedMarker.type === 'nearby'">
            <h3>{{ selectedMarker.data.title }}</h3>
            <p><strong>地址:</strong> {{ selectedMarker.data.address || '暂无地址' }}</p>
            <p><strong>类别:</strong> {{ selectedMarker.data.category || '未知' }}</p>
          </div>
          <div v-else-if="selectedMarker.type === 'search'">
            <h3>{{ selectedMarker.data.title }}</h3>
            <p><strong>地址:</strong> {{ selectedMarker.data.address || '暂无地址' }}</p>
            <p><strong>类别:</strong> {{ selectedMarker.data.category || '未知' }}</p>
            <p><strong>距离:</strong> {{ selectedMarker.data.distance || 0 }}米</p>
          </div>
          <div v-else-if="selectedMarker.type === 'userLocation'">
            <h3>我的位置</h3>
            <p><strong>地址:</strong> {{ selectedMarker.data.address || '当前位置' }}</p>
          </div>
        </InfoWindow>
      </BaseMap>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { getActivities, searchNearbyActivities, searchPlaces } from '@/services/mapApi';

export default defineComponent({
  name: 'MapExplorer',
  setup() {
    // 腾讯地图配置
    const mapKey = 'KV5BZ-6VR3T-EPJXZ-VXGCD-K5N35-2WFB6'; // 使用用户提供的API Key
    const center = ref({ lat: 39.908823, lng: 116.397470 }); // 默认中心点：北京
    const zoom = ref(12);
    const searchRadius = ref(1000); // 搜索半径，默认1公里
    const searchKeyword = ref('');
    const selectedCategory = ref('');
    const showCategoryResults = ref(false);
    const categoryResults = ref([]);
    const categoryLoading = ref(false);
    const mapRef = ref();
    const mapInstance = ref();
    const markers = ref([]);
    const selectedMarker = ref(null);
    const infoWindowVisible = ref(false);
    const showNearbyDropdown = ref(false);
    const mockDataLoading = ref(false);
    const mockNearbyData = ref([]);
    const selectedMockItem = ref(null);

    const onMapLoaded = (map) => {
      mapInstance.value = map;
    };

    const onMapClick = (event) => {
      infoWindowVisible.value = false;
      selectedMarker.value = null;
    };

    const onMarkerClick = (marker) => {
      selectedMarker.value = marker;
      infoWindowVisible.value = true;
    };

    const loadActivities = async () => {
      try {
        const response = await getActivities();
        markers.value = response.data
          .filter(activity => activity && activity.latitude && activity.longitude)
          .map(activity => ({
            id: `activity-${activity.id}`,
            type: 'activity',
            position: { lat: activity.latitude, lng: activity.longitude },
            data: activity,
            options: {
              title: activity.name,
              icon: '/marker-activity.png'
            }
          }));
      } catch (error) {
        console.error('加载活动数据失败:', error);
      }
    };

    const performSearch = async () => {
      console.log('开始搜索:', searchKeyword.value);
      if (!searchKeyword.value.trim()) {
        console.log('搜索关键词为空');
        return;
      }
      
      try {
        console.log('调用搜索API...');
        const response = await searchPlaces(
          searchKeyword.value,
          center.value.lat,
          center.value.lng
        );
        
        console.log('API响应:', response);
        
        // searchPlaces 函数直接返回数据数组
        const searchResults = response || [];
        console.log('搜索结果数量:', searchResults.length);
        
        markers.value = searchResults
          .filter(place => place && (place.location || center.value))
          .map((place, index) => ({
            id: `search-${index}`,
            type: 'search',
            position: { 
              lat: place.location?.lat || center.value.lat,
              lng: place.location?.lng || center.value.lng
            },
          data: {
            title: place.name || '未知地点',
            address: place.address || '地址不详',
            category: place.category || '未知',
            distance: place.distance || 0
          },
          options: {
            title: place.name || '未知地点',
            icon: '/marker-search.png'
          }
        }));
        
        console.log('标记点已更新');
        
        // 如果有搜索结果，调整地图视图到第一个结果的位置
        if (searchResults.length > 0 && searchResults[0].location) {
          const firstResult = searchResults[0];
          center.value = {
            lat: firstResult.location.lat,
            lng: firstResult.location.lng
          };
          // 稍微缩小地图以显示周围区域
          zoom.value = Math.max(zoom.value - 2, 12);
          console.log('地图已跳转到搜索结果位置');
        }
      } catch (error) {
        console.error('搜索失败:', error);
      }
    };

    const toggleNearbyDropdown = async () => {
      showNearbyDropdown.value = !showNearbyDropdown.value;
      
      if (showNearbyDropdown.value && mockNearbyData.value.length === 0) {
        mockDataLoading.value = true;
        
        try {
          const response = await searchNearbyActivities(
            center.value.lat,
            center.value.lng,
            searchRadius.value
          );
          // 如果API返回空数据，使用模拟数据
          mockNearbyData.value = response.data && response.data.length > 0 ? response.data : [
            {
              title: '咖啡厅',
              address: '北京市朝阳区',
              category: '餐饮',
              distance: 500
            },
            {
              title: '公园',
              address: '北京市东城区',
              category: '休闲',
              distance: 800
            },
            {
              title: '商场',
              address: '北京市海淀区',
              category: '购物',
              distance: 1200
            }
          ];
        } catch (error) {
          console.error('加载附近数据失败:', error);
          // 使用模拟数据作为备选
          mockNearbyData.value = [
            {
              title: '咖啡厅',
              address: '北京市朝阳区',
              category: '餐饮',
              distance: 500
            },
            {
              title: '公园',
              address: '北京市东城区',
              category: '休闲',
              distance: 800
            },
            {
              title: '商场',
              address: '北京市海淀区',
              category: '购物',
              distance: 1200
            }
          ];
        } finally {
          mockDataLoading.value = false;
        }
      }
    };

    const selectNearbyItem = (item) => {
      selectedMockItem.value = item;
      // 在地图上添加标记
      markers.value.push({
        id: `nearby-${Date.now()}`,
        type: 'nearby',
        position: center.value,
        data: item,
        options: {
          title: item.title,
          icon: '/marker-nearby.png'
        }
      });
      // 选择后自动关闭下拉框
      showNearbyDropdown.value = false;
    };

    const selectMockItem = (item) => {
      selectedMockItem.value = item;
    };

    const searchByCategory = async () => {
      if (!selectedCategory.value) {
        showCategoryResults.value = false;
        return;
      }
      
      categoryLoading.value = true;
      showCategoryResults.value = true;
      
      try {
        // 首先获取用户当前位置
        if (!navigator.geolocation) {
          throw new Error('浏览器不支持定位功能');
        }
        
        const position = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject, {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 300000
          });
        });
        
        const userLocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        
        // 更新地图中心到用户位置
        center.value = userLocation;
        zoom.value = 15;
        
        // 调用API搜索附近分类场所
        const response = await searchPlaces(
          selectedCategory.value,
          userLocation.lat,
          userLocation.lng,
          searchRadius.value
        );
        
        // 处理搜索结果
        categoryResults.value = (response || []).map((place, index) => ({
          id: `category-${index}`,
          title: place.name || selectedCategory.value,
          address: place.address || '地址不详',
          category: selectedCategory.value,
          distance: place.distance || Math.floor(Math.random() * 2000) + 100,
          location: place.location || userLocation
        }));
        
        // 在地图上添加标记
        markers.value = markers.value.filter(marker => marker && marker.id && !marker.id.startsWith('category-'));
        // 确保所有marker都有position属性
        markers.value = markers.value.filter(marker => marker && marker.position);
        markers.value.push(...categoryResults.value
          .filter(item => item && item.location)
          .map(item => ({
            id: item.id,
            type: 'category',
            position: item.location,
            data: item,
            options: {
              title: item.title,
              icon: '/marker-category.png'
            }
          })));
        
      } catch (error) {
        console.error('分类搜索失败:', error);
        // 使用模拟数据作为备选
        categoryResults.value = [
          {
            id: 'category-1',
            title: `${selectedCategory.value}1`,
            address: '模拟地址1',
            category: selectedCategory.value,
            distance: 500,
            location: center.value
          },
          {
            id: 'category-2',
            title: `${selectedCategory.value}2`,
            address: '模拟地址2',
            category: selectedCategory.value,
            distance: 800,
            location: { lat: center.value.lat + 0.002, lng: center.value.lng + 0.002 }
          },
          {
            id: 'category-3',
            title: `${selectedCategory.value}3`,
            address: '模拟地址3',
            category: selectedCategory.value,
            distance: 1200,
            location: { lat: center.value.lat - 0.002, lng: center.value.lng - 0.002 }
          }
        ];
      } finally {
        categoryLoading.value = false;
      }
    };

    const selectCategoryItem = (item) => {
      // 跳转到选中项的位置
      center.value = item.location;
      zoom.value = 16;
      
      // 高亮选中的标记
      const marker = markers.value.find(m => m.id === item.id);
      if (marker) {
        selectedMarker.value = marker;
        infoWindowVisible.value = true;
      }
    };

    const closeCategoryResults = () => {
      showCategoryResults.value = false;
      selectedCategory.value = '';
      // 移除分类相关的标记
      markers.value = markers.value.filter(marker => marker && marker.id && !marker.id.startsWith('category-'));
      // 确保所有marker都有position属性
      markers.value = markers.value.filter(marker => marker && marker.position);
    };



    const locateUser = () => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const userLocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            
            center.value = userLocation;
            zoom.value = 15;
            
            markers.value.push({
              id: 'user-location',
              type: 'userLocation',
              position: userLocation,
              data: {
                address: '当前位置',
                lat: position.coords.latitude,
                lng: position.coords.longitude,
                accuracy: position.coords.accuracy
              },
              options: {
                title: '我的位置',
                icon: '/marker-user.png'
              }
            });
          },
          (error) => {
            console.error('获取位置失败:', error);
          },
          { enableHighAccuracy: true, timeout: 10000, maximumAge: 300000 }
        );
      }
    };

    const getCategoryLabel = (category) => {
      const categories = {
        'dining': '餐饮',
        'entertainment': '娱乐',
        'shopping': '购物',
        'sports': '运动',
        'education': '教育',
        'medical': '医疗'
      };
      return categories[category] || category;
    };

    const getItemIcon = (category) => {
      const icons = {
        '餐饮': '🍽️',
        '休闲': '🏖️',
        '购物': '🛒',
        '运动': '⚽',
        '教育': '📚',
        '医疗': '🏥'
      };
      return icons[category] || '📍';
    };

    return {
      mapKey,
      center,
      zoom,
      searchRadius,
      searchKeyword,
      selectedCategory,
      showCategoryResults,
      categoryResults,
      categoryLoading,
      mapRef,
      markers,
      selectedMarker,
      infoWindowVisible,
      showNearbyDropdown,
      mockDataLoading,
      mockNearbyData,
      selectedMockItem,
      onMapLoaded,
      onMapClick,
      onMarkerClick,
      loadActivities,
      performSearch,
      toggleNearbyDropdown,
      selectNearbyItem,
      searchByCategory,
      selectCategoryItem,
      closeCategoryResults,
      locateUser,
      getCategoryLabel,
      getItemIcon
    };
  }
});
</script>

<style scoped>

.map-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.controls {
  padding: 28px;
  background: var(--color-surface);
  border-bottom: 1px solid var(--color-outline);
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
  position: relative;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 20px;
  background: linear-gradient(135deg, var(--color-primary) 0%, #A3826B 100%);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 500;
  font-size: 14px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.action-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s ease;
}

.action-btn:hover::before {
  left: 100%;
}

.action-btn:hover {
  background: linear-gradient(135deg, #A3826B 0%, var(--color-primary) 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.3);
}

.action-btn:focus-visible {
  box-shadow: 0 0 0 3px rgba(139, 115, 85, 0.25), 0 0 0 1.5px var(--color-primary) inset;
}

.search-container {
  display: flex;
  gap: 10px;
}

.search-input {
  padding: 12px 16px;
  border: 1px solid var(--color-outline);
  border-radius: 12px;
  min-width: 280px;
  background: white;
  font-size: 14px;
  transition: all 0.2s ease;
}

.search-input:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(139, 115, 85, 0.1);
}



.radius-select {
  padding: 12px 16px;
  border: 1px solid var(--color-outline);
  border-radius: 12px;
  background: white;
  font-size: 14px;
  min-width: 120px;
}

.map-wrapper {
  flex: 1;
  position: relative;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: var(--color-surface);
  border-radius: 16px;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
  border: 1px solid var(--color-outline);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.modal-header {
  padding: 24px;
  border-bottom: 1px solid var(--color-outline);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: var(--color-surface-variant);
}

.modal-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: var(--color-primary);
  margin: 0;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  transition: color 0.2s ease, transform 0.2s ease;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button:hover {
  color: var(--color-primary);
  background: rgba(139, 115, 85, 0.1);
  transform: scale(1.1);
}

.close-button:focus-visible {
  outline: 2px solid var(--color-primary);
  outline-offset: 2px;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
}

.loading {
  text-align: center;
  padding: 40px;
}

.mock-data-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.mock-data-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid var(--color-outline);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
}

.mock-data-item:hover {
  background: var(--color-surface-variant);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.1);
}

.item-icon {
  font-size: 24px;
  margin-right: 12px;
}

.item-content h3 {
  margin: 0 0 6px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text);
}

.item-address {
  margin: 0;
  color: var(--color-text-secondary);
  font-size: 14px;
  line-height: 1.4;
}

.item-distance {
  margin: 4px 0 0 0;
  color: var(--color-primary);
  font-size: 14px;
  font-weight: 600;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #ddd;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

/* 下拉框样式 */
.nearby-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  margin-top: 8px;
  z-index: 1000;
  background: white;
  border: 1px solid var(--color-outline);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  min-width: 320px;
  max-height: 400px;
  overflow: hidden;
}

.dropdown-content {
  padding: 16px;
  max-height: 368px;
  overflow-y: auto;
}

.nearby-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.nearby-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid var(--color-outline);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
}

.nearby-item:hover {
  background: var(--color-surface-variant);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.1);
  border-color: var(--color-primary);
}

/* 分类搜索结果样式 - 从左侧弹出 */
.category-results {
  position: absolute;
  top: 120px; /* 距离顶部固定高度，不超出地图 */
  left: 20px;
  z-index: 1000;
  background: white;
  border: 1px solid var(--color-outline);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  width: 350px;
  max-height: calc(100vh - 160px); /* 不超过地图高度 */
  overflow: hidden;
}

.results-header {
  padding: 16px;
  border-bottom: 1px solid var(--color-outline);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: var(--color-surface-variant);
}

.results-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-primary);
}

.close-results-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
  transition: color 0.2s ease;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-results-btn:hover {
  color: var(--color-primary);
  background: rgba(139, 115, 85, 0.1);
}

.results-list {
  padding: 16px;
  overflow-y: auto;
  max-height: 400px;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid var(--color-outline);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
  margin-bottom: 8px;
}

.result-item:hover {
  background: var(--color-surface-variant);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.1);
  border-color: var(--color-primary);
}

.result-item:last-child {
  margin-bottom: 0;
}

.result-item .item-icon {
  font-size: 20px;
  margin-right: 12px;
  flex-shrink: 0;
}

.result-item .item-content {
  flex: 1;
}

.result-item .item-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text);
}

.result-item .item-address {
  margin: 0;
  color: var(--color-text-secondary);
  font-size: 12px;
  line-height: 1.3;
}

.result-item .item-distance {
  margin: 4px 0 0 0;
  color: var(--color-primary);
  font-size: 12px;
  font-weight: 600;
}

/* 分类选择器样式 */
.category-select {
  padding: 12px 16px;
  border: 1px solid var(--color-outline);
  border-radius: 12px;
  background: white;
  font-size: 14px;
  min-width: 140px;
  height: 44px;
}

.category-select:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(139, 115, 85, 0.1);
}
</style>